/**
 * @file 工单操作-赔偿单
 */
layui.define(['layer', 'list_modify_common', 'form', 'table', 'zmnUtils', '$http', 'clipboard', 'NP', 'upload'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var config = layui.oms_work_config;
    var opCommonUtils = layui.list_modify_common;
    let table = layui.table;

    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var clipboard = layui.clipboard;
    var NP = layui.NP;
    let upload = layui.upload;
    let timestamp = new Date().getTime();

    var SAVE_COMPENSATE_URL = '/work/modify/save/compensate.action';
    var UPDATE_COMPENSATE_URL = '/work/modify/update/compensate.action';

    /**
     * 判断是否是正整数且最多小数点后两位;
     * @param val {number/string} 字符串或数字
     * @returns {boolean} 返回是否是数字
     */
    function isNumber(val) {
        var reg = /^(\-|\+)?\d+([.]{1}\d{1,2})?$/;//正负整数到小数点后两位
        return reg.test(val);
    }

    /**
     * 验证
     */
    function defineVerify() {
        form.verify({
            amount: function (val) {
                if (val > 1000000 || val < 0) {
                    return "范围在零到一百万之间";
                }
                if (!isNumber(val)) {
                    return "金额不合规范";
                }
            },
            content: function (val) {

            },
            damageGood: function (val) {
                if (val.toString().length > 50) {
                    return "最多输入50位";
                }
            }
        })
    }

    /**
     * 初始化页面
     */
    function initPage() {
        //验证
        defineVerify();

        // 初始化剪切板控制器
        clipboard.init();

        // 初始化文件上传插件
        for (let i = 0; i < 5; i++) {
            uploaderImage("imageSrcUrl" + i, "imageSrcUrl" + i + "Value", i);
        }

        let indexUploadImags;

        function uploaderImage(elemId, valueId, index) {
            upload.render({
                elem: '#' + elemId
                , exts: 'jpg|png|jpeg'
                , acceptMime: 'image/*'
                , accept: 'images'
                , url: '/work/modify/uploader/orderPhoto?timestamp=' + timestamp + '&elemId=' + elemId
                , size: 5120
                , beforeSend: function (obj) {
                    indexUploadImags = layui.layer.load(1, {
                        shade: [0.5, '#DBDBDB']
                    });
                }
                , done: function (res) {
                    if (res.statusBool) {
                        let data = res.data;
                        $("#" + valueId).val(data);
                        $("#" + valueId + "s").attr("src", data).attr("style", "width: 0;height: 0");
                        reLoadImage(elemId, data);
                    } else {
                        layer.msg(res.message);
                    }
                    layui.layer.close(indexUploadImags);
                }
            });
        }

        function reLoadImage(elemId, value, valueId) {
            zmnUploadUtil.reLoadImage($, elemId, value, valueId);
            let next = $("#" + elemId + "Value").next();
            let next1 = $(next).next();
            $(next).attr("style", "visibility:hidden !important");
            $(next1).attr("style", "visibility:hidden !important");
        }

        // 回显附件
        if (images) {
            images.forEach(function (data, index) {
                reLoadImage("imageSrcUrl" + index, data);
                $("#imageSrcUrl" + index + "Value").val(data);
                $("#imageSrcUrl" + index + "Values").attr("src", data).attr("style", "width: 0;height: 0");
            });
        }
    }

    function normalizeCompensateParams(data) {
        switch (data.payTargetChannelId) {
            case "":
                break;
            case "1" :
                data.payeeThirdAccount = $('#alipayInfo input[name="payeeThirdAccount"]').val();
                data.payeeThirdAccountName = $('#alipayInfo input[name="payeeThirdAccountName"]').val();
                data.payeeThirdAccountBank = '';
                break;
            case "2" :
                data.payeeThirdAccount = $('#weixinInfo input[name="payeeThirdAccount"]').val();
                data.payeeThirdAccountName = $('#weixinInfo input[name="payeeThirdAccountName"]').val();
                data.payeeThirdAccountBank = '';
                break;
            case "5" :
                let payeeThirdAccount = $('#bankInfo input[name="payeeThirdAccount"]').val();
                data.payeeThirdAccount = payeeThirdAccount.replaceAll(" ", "");
                data.payeeThirdAccountName = $('#bankInfo input[name="payeeThirdAccountName"]').val();
                data.payeeThirdAccountBank = $('#bankInfo input[name="payeeThirdAccountBank"]').val();
                break;
            case "31" :
                data.payeeThirdAccount = '';
                data.payeeThirdAccountName = '';
                data.payeeThirdAccountBank = '';
                break;
        }
    }

    function normalizeParams(data) {
        data.compensateAmount = zmnUtils.unit.YuanToFen(+data.compensateAmount);
        normalizeCompensateParams(data);
        return data;
    }

    function saveCompensate(params, elem) {
        var url = '';
        if (isUpdate) {
            url = UPDATE_COMPENSATE_URL;
        } else {
            url = SAVE_COMPENSATE_URL;
        }
        $http.lockSave(url, params, elem).then(function (data) {
            zmnUtils.layui.toastSuccess('操作成功', function () {
                opCommonUtils.goSomeWorkDetail(data);
            });
        }, function (msg) {
            zmnUtils.layui.toastError(msg || '操作失败');
        });
    }

    function getImageList() {
        let imageList = [];
        for (let i = 0; i < 5; i++) {
            var imageUrl = $('#imageSrcUrl' + i + 'Value').val();
            if (imageUrl) {
                imageList.push(imageUrl);
            }
        }
        return imageList;
    }

    function verifyCompensateType(formData){
        if (!formData.payTargetChannelId) {
            layer.msg('请选择赔偿方式！');
            return false;
        }
        let payeeThirdAccount;
        let payeeThirdAccountName;
        let payeeThirdAccountBank;
        switch (formData.payTargetChannelId) {
            case "1" :
                payeeThirdAccount = $('#alipayInfo input[name="payeeThirdAccount"]').val();
                payeeThirdAccountName = $('#alipayInfo input[name="payeeThirdAccountName"]').val();
                if (!payeeThirdAccount || !payeeThirdAccountName) {
                    layer.msg('请填写账户信息');
                    return false;
                }
                break;
            case "2" :
                payeeThirdAccount = $('#weixinInfo input[name="payeeThirdAccount"]').val();
                payeeThirdAccountName = $('#weixinInfo input[name="payeeThirdAccountName"]').val();
                if (!payeeThirdAccount || !payeeThirdAccountName) {
                    layer.msg('请填写账户信息');
                    return false;
                }
                break;
            case "5" :
                payeeThirdAccount = $('#bankInfo input[name="payeeThirdAccount"]').val();
                payeeThirdAccount = payeeThirdAccount.replaceAll(" ", "");
                payeeThirdAccountName = $('#bankInfo input[name="payeeThirdAccountName"]').val();
                payeeThirdAccountBank = $('#bankInfo input[name="payeeThirdAccountBank"]').val();
                if (!payeeThirdAccount || !payeeThirdAccountName || !payeeThirdAccountBank) {
                    layer.msg('请填写账户信息');
                    return false;
                }
                var regPos = /^\d+(\d+)?$/; //非负浮点数
                if (!regPos.test(payeeThirdAccount)) {
                    layer.msg('银行卡号只能填写数字');
                    return false;
                }
                break;
        }
        return true;
    }

    function chageOpenHtml(payTargetChannelId) {
        // 切换显示内容
        switch (payTargetChannelId) {
            case '1':
                $('#alipayInfo').show();
                $('#weixinInfo').hide();
                $('#bankInfo').hide();
                $('#cashInfo').hide();
                break;
            case '2':
                $('#weixinInfo').show();
                $('#alipayInfo').hide();
                $('#bankInfo').hide();
                $('#cashInfo').hide();
                break;
            case '5':
                $('#bankInfo').show();
                $('#alipayInfo').hide();
                $('#weixinInfo').hide();
                $('#cashInfo').hide();
                break;
            case '31':
                $('#cashInfo').show();
                $('#bankInfo').hide();
                $('#alipayInfo').hide();
                $('#weixinInfo').hide();
                break;
        }

    }

    function getMapName(mapId) {
        for (var i = 0; i < compensateReasonList.length; i++) {
            var reasonListElement = compensateReasonList[i];
            if (reasonListElement.value.toString() === mapId) {
                return reasonListElement.text;
            }
        }
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        // 监听表单提交
        form.on("submit()", function (obj) {
            var formData = obj.field;
            formData.payTargetChannelId = $('input:radio[name="payTargetChannelId"]:checked').val();
            if (!verifyCompensateType(formData)) {
                return false;
            }

            var reasonList = [];
            var formDataArr = $(obj.form).serializeArray();
            for (var i = 0; i < formDataArr.length; i++) {
                var formDatum = formDataArr[i];
                if (formDatum.name === 'compensateReason') {
                    var OrderRemarkDetailDTO = {
                        value: formDatum.value,
                        text: getMapName(formDatum.value)
                    };
                    reasonList.push(OrderRemarkDetailDTO);
                }
            }

            if (reasonList.length == 0) {
                layer.msg("请选择赔偿原因！");
                return false;
            }


            let imageList = getImageList();
            var params = normalizeParams(formData);
            params.imageUrls = imageList;
            params.reasonList = reasonList;
            // 保存
            saveCompensate(params, obj.elem);
            return false;
        });


        // 退款方式
        form.on('radio(payTargetChannelId)', function (data) {
            chageOpenHtml(data.value);
        });

        // 监听 定金变化
        $('#amount').on('change', function () {
            var val = $(this).val();
            if (val > 1000000 || val < 0) {
                layer.msg("范围在0-1000000之间");
                $("#amount").val("");
            }
            if (!isNumber(val)) {
                layer.msg("请输入最多两位小数");
                $("#amount").val("");
            }
        });

        // 点击放大
        $(document).on('click', '.btn-review', function () {
            let $container = $(this).parent().prev();
            $container.viewer().on('hide', function () {
                $container.viewer('destroy');
            });

            let index = $(this).index();
            $container.viewer('view', index);

        });
        // 点击删除
        $(document).on('click', '.btn-delete', function () {
            let $uploadDiv = $(this).parent().prev();
            $uploadDiv.find(".layui-upload-drag").attr("style", "");
            $uploadDiv.find("i").attr("style", "");
            $uploadDiv.find("p").attr("style", "");
            $uploadDiv.find(":hidden").val("");

            let index = $(this).data('index');
            $('#refund_no_input' + index).attr('lay-verify', '');
        });
    }


    // 程序入口
    function init() {
        // 初始化页面
        initPage();
        // 初始化事件
        initEvent();
    }

    // 初始化
    init();

    exports('oms_work_modify_compensate');
});
